package com.disapand.strongarmy.utils

import cn.hutool.core.lang.tree.*
import com.disapand.strongarmy.model.*
import com.disapand.strongarmy.vo.permission.*

/**
 *
 * @auth disapand
 * @date 2021/10/29 - 17:50 - 星期五
 *
 */
class SaUtils {

    companion object {
        /**
         * 格式化 uri 成类似 “/user” 前加 “/” 的形式
         *
         * @param uri
         * @return
         */
        fun generateURI(uri: String): String {
            return if (uri.startsWith("/")) {
                uri
            } else {
                "/$uri"
            }
        }

        /**
         * 将菜单转换成树形
         *
         * @param menus
         * @return
         */
        fun generateMenuTree(menus: List<Menu>): List<Tree<Int>> {
            val config = TreeNodeConfig()
            config.parentIdKey = "parent_id"

            return TreeUtil.build(menus, 0, config) { menu: Menu, tree: Tree<Int> ->
                tree.id = menu.id
                tree.name = menu.name
                tree.parentId = menu.parentId
                tree.weight = menu.weight
                tree.putExtra("path", menu.path)
                tree.putExtra("icon", menu.icon)
            }
        }

        /**
         * 权限列表转树形
         *
         * @param permissions
         * @return
         */
        fun generatePermissionTree(permissions: List<Permission>): List<PermissionTreeVO> {
            val result: MutableList<PermissionTreeVO> = mutableListOf()
            permissions.forEach { permission ->
                val exist = result.any { it.group == permission.group }
                if (exist) {
                    val res = result.filter { r -> r.group == permission.group }
                    val childrenList = res[0].children.toMutableList()
                    childrenList.add(permission)
                    res[0].children = childrenList
                } else {
                    result.add(PermissionTreeVO(permission.group, permission.groupLabel, listOf(permission)))
                }
            }
            return result
        }

    }
}